import { useRef } from "react";
import { Image, message, Descriptions, Button, Popconfirm } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormDigit,
} from "@ant-design/pro-form";
import useCommonTable from "@/hooks/useCommonTable";
import { history } from "umi";
import {
  fetchOtherOrderList,
  deliverySubmitJdOrderOther,
  refund,
  getPrintDataOther,
} from "@/api/order";
import {
  otheOrderStatusOptions,
  deliveryStatusOptions,
  filterDeliveryStatusOptions,
} from "@/const";
import sendMsg2Print from "@/ws";

export default () => {
  const columns = [
    {
      title: "订单号",
      dataIndex: "orderNo",
      search: false,
    },
    {
      title: "订单状态",
      dataIndex: "orderStatus",
      valueType: "select",
      fieldProps: {
        options: otheOrderStatusOptions,
      },
    },
    {
      title: "物流状态",
      search: false,
      dataIndex: "deliveryStatus",
      valueType: "select",
      fieldProps: {
        options: deliveryStatusOptions,
      },
      render: (_, record) => {
        // 已支付的才展示物流状态
        return record.orderStatus == 2
          ? filterDeliveryStatusOptions(record.deliveryStatus)
          : "-";
      },
    },
    {
      title: "用户名称",
      dataIndex: "userName",
    },
    {
      title: "手机号",
      dataIndex: "mobile",
    },
    {
      title: "名称",
      dataIndex: "name",
      search: false,
      render: (_, record) => {
        return record.bizObj?.name;
      },
    },

    {
      title: "付款金额",
      dataIndex: "orderMoney",
      search: false,
      render: (_, record) => {
        return <>￥{record.orderMoney}</>;
      },
    },
    {
      title: "退款金额",
      dataIndex: "refundMoney",
      search: false,
      render: (_, record) => {
        return <>{record.refundMoney ? `￥${record.refundMoney}` : ""}</>;
      },
    },
    {
      title: "购买时间",
      dataIndex: "createTime",
      search: false,
    },
  ];

  const renderDetailFormModal = (record) => {
    return (
      <ModalForm
        key="detail"
        title="订单详情"
        width={800}
        layout="horizontal"
        submitter={false}
        trigger={<Button style={{ marginRight: 8 }}>详情</Button>}
      >
        <Descriptions title="订单信息" column={2}>
          <Descriptions.Item label="订单号">{record.orderNo}</Descriptions.Item>
          <Descriptions.Item label="购买用户">
            {record.bizObj?.name}
          </Descriptions.Item>
          <Descriptions.Item label="老师姓名">
            {record.bizObj?.name}
          </Descriptions.Item>
          <Descriptions.Item label="老师手机号">
            {record.bizObj?.phone}
          </Descriptions.Item>
          <Descriptions.Item label="购买时间">
            {record.createTime}
          </Descriptions.Item>
          <Descriptions.Item label="课时">
            {record.purchaseNum}
          </Descriptions.Item>
          <Descriptions.Item label="金额">
            {record.orderMoney}
          </Descriptions.Item>
        </Descriptions>

        <Descriptions title="核销信息" column={1}>
          <Descriptions.Item label="已核销">
            {record.serviceNum || 0}课时
          </Descriptions.Item>
          <Descriptions.Item label="核销记录"></Descriptions.Item>
        </Descriptions>
      </ModalForm>
    );
  };
  const formRef = useRef();

  // 退款
  const renderReturnMoneyFormModal = (record, actionRef) => {
    const handleAddOrUpdate = async (fields) => {
      const postData = {
        orderId: record.id,
        ...fields,
      };
      const res = await refund(postData);
      if (res.data) {
        message.success("退款成功");
        actionRef?.current.reload();
        return true; // 关闭弹框
      }
    };

    return (
      <ModalForm
        key="refund"
        labelCol={{
          span: 4,
        }}
        formRef={formRef}
        layout="horizontal"
        title="退款"
        width={600}
        trigger={
          <Button style={{ marginRight: 10 }} type="danger">
            退款
          </Button>
        }
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            formRef.current?.resetFields();
          },
        }}
        onFinish={async (values) => {
          return await handleAddOrUpdate(values);
        }}
        initialValues={{
          ...record,
        }}
      >
        <ProFormText label="订单金额" disabled name="orderMoney" />
        <ProFormDigit
          label="退款金额"
          name="refundMoney"
          placeholder="请输入退款金额"
          min={0.01}
          max={record.orderMoney}
          rules={[
            { required: true, message: "请输入退款金额" },
            {
              validator: async (_, value) => {
                if (value && value > record.orderMoney) {
                  return Promise.reject(new Error("退款金额不能大于订单金额"));
                }
              },
            },
          ]}
        />
      </ModalForm>
    );
  };
  return (
    <PageContainer>
      {useCommonTable({
        title: "",
        renderAdd: () => {},
        params: {
          starType: 1, //商品类型 1新健康 2星辅育 3新文旅
          starSecondType: 1, // 二级星类型对应关系 1智守护 2测评 3证书 4阅读素养 5写作能力
        },
        columns,
        modalWidth: 400,
        fetchList: fetchOtherOrderList,
        actionColumnWidth: 200,
        showCheckbox: false,
        renderAction: (_, record, renderModalForm, actionRef) => {
          return (
            <>
              {/* {renderDetailFormModal(record)} */}

              {/* 已支付并且订单金额不为0 并且 还没有发货 才能退款 */}
              {record.orderStatus == 2 &&
                record.orderMoney != 0 &&
                record.deliveryStatus == 1 &&
                renderReturnMoneyFormModal(record, actionRef)}

              {/* 已支付 待发货时-才能发货 */}
              {record.orderStatus == 2 && record.deliveryStatus == 1 && (
                <Popconfirm
                  key="send"
                  title="确定发货?"
                  onConfirm={async () => {
                    const res = await deliverySubmitJdOrderOther({
                      id: record.id, //订单id
                    });
                    if (res.data) {
                      actionRef.current?.reload();
                    }
                  }}
                >
                  <Button type="primary">发货</Button>
                </Popconfirm>
              )}

              {/* 已支付 并且发货了 才能打印运单*/}
              {record.orderStatus == 2 && record.deliveryStatus == 2 && (
                <Popconfirm
                  key="print"
                  title="确定打印运单?"
                  onConfirm={async () => {
                    const res = await getPrintDataOther({
                      id: record.id, //订单id
                    });
                    if (res.data) {
                      // webSocket 调起打印
                      sendMsg2Print(res.data);
                      message.success("打印成功");
                      actionRef.current?.reload();
                    }
                  }}
                >
                  <Button type="primary" style={{ marginRight: 8 }}>
                    打印运单
                  </Button>
                </Popconfirm>
              )}
            </>
          );
        },
      })}
    </PageContainer>
  );
};
